//
//  XMGShowPictureViewController.m
//  百思不得姐
//
//  Created by 杨庆 on 2017/1/15.
//  Copyright © 2017年 杨庆. All rights reserved.
//

#import "XMGShowPictureViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "XMGTopic.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "XMGProgressView.h"
@interface XMGShowPictureViewController ()
@property (weak, nonatomic)  UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet XMGProgressView *progressView;

@end

@implementation XMGShowPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];

	// 添加图片
	UIImageView*imageView=[[UIImageView alloc]init];
	[self.scrollView addSubview:imageView];
	
	// 图片添加手势
	imageView.userInteractionEnabled=YES;
	UIGestureRecognizer*gesture=[[UIGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
	[imageView addGestureRecognizer:gesture];
	self.imageView = imageView;
	
	// 屏幕宽度
	CGFloat pictureW = [UIScreen mainScreen].bounds.size.width;
	CGFloat pictureH = pictureW *self.topic.height/self.topic.width;
	
	if (pictureH > [UIScreen mainScreen ].bounds.size.height) { // 图片超出屏幕高度范围
		// 需要滚动查看
		self.imageView.frame = CGRectMake(0, 0, pictureW, pictureH);
		self.scrollView.contentSize=CGSizeMake(0, pictureH);
	}else {
		// 不需要滚动
		self.imageView.size = CGSizeMake(pictureW, pictureH);
		self.imageView.centerY = [UIScreen mainScreen].bounds.size.height*0.5; // 图片居中
		
	}
	
	// 马上显示当前下载进度
	[self.progressView setProgress:self.topic.pictureProgress animated:YES];
	
	// 下载大图
	[self.imageView sd_setImageWithURL:[NSURL URLWithString:self.topic.large_image] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
		[self.progressView setProgress:1.0*receivedSize/expectedSize animated:NO];
		
	} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { // 下载完毕隐藏
		self.progressView.hidden = YES;
		
	}];
	
}


-(IBAction)back {
	
	[self dismissViewControllerAnimated:YES completion:nil];
}

// 保存图片到相册
- (IBAction)save:(id)sender {
	if (self.imageView.image == nil) {
		[SVProgressHUD showErrorWithStatus:@"图片未下载完毕! "];
		return;
	}
	// 保存到相册-- 方法名不是,参数是重点
	UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
	
	
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
	
	if (error) {
		//保存失败
		[SVProgressHUD showErrorWithStatus:@"保存失败!"];
	}else{
		[SVProgressHUD showSuccessWithStatus:@"保存成功"];
	}
	
}
@end
